import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../entities';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    @InjectRepository(User)
    private userRepository: Repository<User>
  ) { }

  async validateUser(email: string, password: string): Promise<any> {
    const user = await this.userRepository.findOne({email: email});
    if (user && user.password === password) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: User) {
    const payload = { username: user.name, sub: user.uid };
    return {
      success: true,
      value: this.jwtService.sign(payload),
    };
  }

  async register(user: User): Promise<any> {
    console.log('user', user)
    const isUser = await this.userRepository.find({email: user.email});
    console.log(isUser)
    if (isUser.length) {
      return {success: false, errors: ['邮箱重复！']};
    }
    const suser = new User();
    suser.uid = user.uid;
    suser.name = user.name;
    suser.email = user.email;
    suser.password = user.password;
    console.log('newUser', suser);
    const newUser = await this.userRepository.save(suser);
    const payload = { username: newUser.name, sub: newUser.uid };
    return {
      success: true,
      messages: ['注册成功！'],
      value: this.jwtService.sign(payload),
    };
    
  }
}
